package com.specialtreasure.freightdepot;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.app.core.activity.BaseNewActivity;
import com.app.core.config.Constants;
import com.app.core.config.HttpApi;
import com.app.core.presenter.DataCallback;
import com.app.core.presenter.ParamUtils;
import com.app.core.presenter.ParseData;
import com.app.core.presenter.ParseDataImpl;
import com.app.core.util.GetJsonDataUtil;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.utils.HttpUtils;
import com.specialtreasure.freightdepot.dialog.SureDialogFragment;
import com.specialtreasure.freightdepot.fragment.ShareCarFragment;
import com.specialtreasure.freightdepot.model.BaseModel;
import com.specialtreasure.freightdepot.model.JsonBean;
import com.specialtreasure.freightdepot.service.DownLoadService;
import com.vondear.rxtools.RxAppUtils;
import com.vondear.rxtools.view.RxToast;
import com.vondear.rxtools.view.cardstack.RxAdapterStack;
import com.vondear.rxtools.view.dialog.RxDialogChooseImage;
import com.vondear.rxtools.view.dialog.RxDialogLoading;
import com.vondear.rxtools.view.dialog.RxDialogShapeLoading;
import com.vondear.rxtools.view.dialog.dialogShapeLoadingView.RxShapeLoadingView;
import com.yanzhenjie.httpmodule.http.CallServer;
import com.yanzhenjie.httpmodule.http.Result;
import com.yanzhenjie.httpmodule.http.StringRequest;
import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.download.DownloadListener;
import com.yanzhenjie.nohttp.download.DownloadQueue;
import com.yanzhenjie.nohttp.download.DownloadRequest;
import com.yanzhenjie.nohttp.download.SimpleDownloadListener;
import com.yanzhenjie.nohttp.download.SyncDownloadExecutor;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.OnResponseListener;
import com.yanzhenjie.nohttp.rest.RequestQueue;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;

import org.json.JSONArray;
import org.xutils.http.RequestParams;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


/**
 * 主页面
 */
public class TestActivity extends BaseNewActivity implements View.OnClickListener, DataCallback {

    private TextView tv_text;
    private FrameLayout fl_content;
    private RelativeLayout rl_root;
    String url = "http://gdown.baidu.com/data/wisegame/f98d235e39e29031/baiduxinwen.apk";

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private boolean isLoaded = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_test);
        initView();
        getPermission();
    }


    private void initView() {
        tv_text = (TextView) findViewById(R.id.tv_text);
        fl_content = (FrameLayout) findViewById(R.id.fl_con);
        rl_root = (RelativeLayout) findViewById(R.id.rl_root);
        tv_text.setOnClickListener(this);


        mHandler.sendEmptyMessage(MSG_LOAD_DATA);

    }

    private void getData() {
        ParseData parseData = new ParseDataImpl();
        parseData.commonRequest(this, Constants.ZERO, ParamUtils.getUserParam("zhanghao1", "123456"));

    }

    @Override
    public void handleData(int what, String response) {
        switch (what) {
            case Constants.ZERO:
                BaseModel model = JSON.parseObject(response, BaseModel.class);
                tv_text.setText(model.getMsg());
                break;
        }
    }

    @Override
    public void handleErrorMessage(int what, String message) {
        switch (what) {
            case Constants.ZERO:

                break;
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_text:
//                getData();
                ShowPickerView();
                break;
        }
    }










    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText()+
                        options2Items.get(options1).get(options2)+
                        options3Items.get(options1).get(options2).get(options3);

                Toast.makeText(TestActivity.this,tx,Toast.LENGTH_SHORT).show();
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        pvOptions.setPicker(options1Items);//一级选择器
//        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
//        pvOptions.setPicker(options1Items, options2Items,options3Items);//三级选择器
        pvOptions.show();
    }


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread==null){//如果已创建就不再重新创建子线程了

                        Toast.makeText(TestActivity.this,"Begin Parse Data",Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    Toast.makeText(TestActivity.this,"Parse Succeed",Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(TestActivity.this,"Parse Failed",Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };


    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this,"province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i=0;i<jsonBean.size();i++){//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c=0; c<jsonBean.get(i).getCityList().size(); c++){//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        ||jsonBean.get(i).getCityList().get(c).getArea().size()==0) {
                    City_AreaList.add("");
                }else {

                    for (int d=0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }





//    private void getDownLoad() {
//        String url = "http://gdown.baidu.com/data/wisegame/f98d235e39e29031/baiduxinwen.apk";
//        DownloadRequest downloadRequest = new DownloadRequest(url, RequestMethod.GET, Environment.getExternalStorageDirectory().getAbsolutePath(), true, true);
//        DownloadQueue queue = NoHttp.newDownloadQueue(); // 默认三个并发，此处可以传入并发数量。
//        queue.start();
//
//    }

    /**
     * 多权限申请
     */
    private void getPermission() {
        AndPermission.with(this)
                .permission(Permission.CAMERA, Permission.PHONE, Permission.LOCATION) // 多个权限组。
                .requestCode(300)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> list) {
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> list) {
                    }
                })
                .start();
    }


    @Override
    public String getActiviyName() {
        return TAG;
    }
}
